package com.example.GlobalExceptionHandle;

import com.example.Exception.ContactException;
import com.example.Pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result exceptionHandler(Exception e){
        log.error("服务器发生异常：{}",e.getMessage());
        return Result.error("服务器发生异常");
    }

    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e){
        log.error("数据库字段重复：{}",e.getMessage());
        String s=e.getMessage();
        int i = s.indexOf("Duplicate entry");
        String s1=s.substring(i);
        String[] arr = s1.split(" ");
        return Result.error(arr[2]+"已存在");
    }
    @ExceptionHandler
    public Result handleException(ContactException e){
        log.error("出现数据库关联异常：{}",e.getMessage());
        return Result.error(e.getMessage());
    }
}
